from nodetypes.formats.mml.Events import EventHandler

from myelin.server.lib.http import ParamValidators
from myelin.server.lib.http import Status

from forms import Commit

class ParamsFetcher(object):
    
    def fetchParams(self, context, source, params, errors):
        defaults = context.defaults
        args = context.request.args
        
        eventData = context.event.data
        
        errors = {}
        params = {}
        
        params['nick'] = ParamValidators.SingleString(
            'nick',
            args,
            errors,
            min=0
        )
        
        params['passwd'] = ParamValidators.SingleString(
            'passwd',
            args,
            errors,
            min=0
        )
        
        params['session-ttl'] = ParamValidators.NumberRange(
            'session-ttl',
            args,
            errors,
            min=int(defaults.session_ttl),
            max=int(defaults.max_session_ttl),
            default=int(defaults.session_ttl)
        )
        
        domains = context.account.domains
        if len(domains) > 1:
            params['domain'] = ParamValidators.SelectOption(
                'domain',
                args,
                errors,
                domains
            )
        else:
            params['domain'] = domains.keys()[0]
            
        return params, errors
    

class EventHandler(EventHandler):
                
    newCommitForm       = Commit.Form
    newParamsFetcher    = ParamsFetcher    
    
    statusType = u'permission'
    eventMessages = [u'permission-denied',]
    
    def process(self, context, source):
        params, errors  = self.newParamsFetcher().fetchParams(
            context,
            source,
            {}, {}
        )
        
        eventData = context.event.data
        
        eventData.status_type = self.statusType
        eventData.status = u'success'
        eventData.params = params
        eventData.errors = errors
        
        eventData.form = self.newCommitForm()
        eventData.stage = 0
        eventData.submits = context.transform.submitEvents[0]
        eventData.msgs = self.eventMessages
        
        context.model = context.nodeType.retrieveModel(context)
        
        return self.newDocument().createDocument(context, source)